/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.service.impl;


import io.renren.common.utils.Constant;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.validator.Assert;
import io.renren.modules.app.dao.UserDao;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import io.renren.modules.sys.entity.SysDictionaryEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysDictionaryService;
import io.renren.modules.sys.vo.PhoneVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Autowired
	private SysDictionaryService sysDictionaryService;

	@Override
	public PageUtils queryPage(Map<String, Object> params, SysUserEntity sysUserEntity) {

		// 非超级管理员只能查看自己添加的用户
		Long userId = sysUserEntity.getUserId();
		if(userId != Constant.SUPER_ADMIN) {
			params.put("create_user_id", userId);
		}

		IPage<UserEntity> page = new Query<UserEntity>().getPage(params);
		IPage<UserEntity> result = baseMapper.queryPage(page, params);
		return new PageUtils(result);
	}

	@Override
	public boolean updateState(UserEntity entity) {
		return updateById(entity);
	}

	@Override
	public void update(UserEntity user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		} else {
			user.setPassword(DigestUtils.sha256Hex(user.getPassword()));
		}
		updateById(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUser(UserEntity user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		} else {
			user.setPassword(DigestUtils.sha256Hex(user.getPassword()));
		}
		save(user);
	}

	@Override
	public List<PhoneVo> checkPhones(List<String> mobiles) {
		// 拿出数据库所有用户
		List<UserEntity> list = this.list();
		List<PhoneVo> rtn = new ArrayList<>();

		int SIZE = list.size();

		PhoneVo vo = null;

		if(mobiles != null && mobiles.size() > 0) {
			for(int i =0, len = mobiles.size(); i < len; i++) {
				String mobile = mobiles.get(i);
				boolean exist = false;

				for(int j = 0; j < SIZE; j ++) {
					if(mobile.equals(list.get(j).getMobile())) {
						exist = true;
						break;
					}
				}
				vo = new PhoneVo(mobile, exist);
				rtn.add(vo);
			}
		}
		return rtn;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean batch(List<UserEntity> lists, Long userId) {
		// 拿出性别字典
		SysDictionaryEntity dictionaryEntity = new SysDictionaryEntity();
		dictionaryEntity.setType("sex");
		List<SysDictionaryEntity> sexList = sysDictionaryService.loadDictionary(dictionaryEntity);

		Map<String, String> sexMap = new HashMap<>();
		for (SysDictionaryEntity item : sexList) {
			sexMap.put(item.getLabel(), item.getValue());
		}

		// 用户初始密码
		String PASSWORD = "123456";

		UserEntity entity = null;
		Date now = new Date();
		for(int i = 0, len = lists.size(); i < len; i++) {
			entity = lists.get(i);
			entity.setCreateUserId(userId);
			entity.setCreateTime(now);
			entity.setPassword(DigestUtils.sha256Hex(PASSWORD));
			entity.setSex(this.getUserSexCode(entity.getSex(), sexMap));
		}
		return this.saveBatch(lists, lists.size());
	}

	@Override
	public UserEntity getUserInfoId(Long userId) {
		UserEntity entity = baseMapper.getUserInfoId(userId);
		return entity;
	}

	@Override
	public List<Map> regl1() {
		return baseMapper.regl1();
	}

	@Override
	public List<Map> regl2() {
		
		List<Map> list = new ArrayList<>();
		Map item1 = this.countRygl2("email", "是否接受安全教育培训");
		Map item2 = this.countRygl2("billing", "是否接受安全技术交底");
		Map item3 = this.countRygl2("address", "是否为特种作业人员");
		Map item4 = this.countRygl2("bank", "是否接种疫苗");

		list.add(item1);
		list.add(item2);
		list.add(item3);
		list.add(item4);

		return list;
	}

	private Map countRygl2(String column, String label) {
		Map<String, String> params = new HashMap<>();
		params.put("column", column);
		params.put("val", "是");
		Map<String, Object> rs = baseMapper.countRygl2(params);
		System.out.println("---------------" + rs);
		int yes = Integer.parseInt(String.valueOf(rs.get("value")));

		params.put("val", "否");
		rs = baseMapper.countRygl2(params);
		int no =Integer.parseInt(String.valueOf(rs.get("value")));

		Map<String, Object> rtn = new HashMap<>();
		rtn.put("label", label);
		rtn.put("yes", yes);
		rtn.put("no", no);

		return rtn;
	}

	/**
	 * 根据中午拿到对应的性别代码
	 * @param sex
	 * @param sexMap
	 * @return
	 */
	private String getUserSexCode(String sex, Map<String, String> sexMap) {
		String code = "";
		if(StringUtils.isNotBlank(sex)) {
			code = sexMap.get(sex);

			if(code == null) {
				code = "";
			}
		}
		return code;
	}

	@Override
	public UserEntity queryByMobile(String mobile) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>()
				.eq("mobile", mobile)
				.eq("status", "1")
				.ne("deleteflag", "1"));
	}

	@Override
	public long login(LoginForm form) {
		UserEntity user = queryByMobile(form.getMobile());
		Assert.isNull(user, "账号不存在或已被锁定");

		System.out.println(form.getPassword() + "=============" + DigestUtils.sha256Hex(form.getPassword()));

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
			throw new RRException("密码错误");
		}

		return user.getUserId();
	}
}
